use bytes::{Bytes, BytesMut};
use regex::bytes::Regex;
use tools::{
	error::buf_err::{FromBufError, ToBufError},
	types::bufs::{FromBuf, ToBuf},
};

///表示一个sip的用户地址相关的内容
///一般为:  "display-name" <sip-URI>[;tag=tag-value][.....]

#[derive(Debug)]
pub struct SipUrl {
	inner: Bytes,
}

///sip-URI 格式  sip:[userinfo@]host[:port][;transport=tcp|udp|tls|sctp][?parameters]
/// 初始过程不进行翻译操作.除非在需要内容的时候才进行翻译
#[derive(Debug, Clone, Default)]
pub struct SipURI {
	inner: Bytes,
}

impl ToBuf for SipURI {
	type Target = BytesMut;

	fn write_to(&self, target: &mut Self::Target) -> Result<(), ToBufError> {
		target.extend_from_slice(&self.inner);

		Ok(())
	}
}

impl PartialEq for SipURI {
	fn eq(&self, other: &Self) -> bool {
		self.inner.eq(&other.inner)
	}
}

impl Eq for SipURI {}

impl SipURI {
	///分析当前的数据,并返回对应的数据出来
	pub fn analyze(&self) -> Option<Vec<&str>> {
		let pan =
			Regex::new("sip:(?:(.*?)@)?(.+?)(?::\\d+))?(?:;transport=(tcp|udp|tls|sctp))?(?:\\?(.*))?")
				.unwrap();

		Some(
			pan
				.captures(&self.inner)?
				.iter()
				.skip(1)
				.map(|it| match it {
					Some(v) => unsafe { std::str::from_utf8_unchecked(v.as_bytes()) },
					None => "",
				})
				.collect(),
		)
	}

	#[inline]
	pub fn new() -> Self {
		Default::default()
	}

	#[inline]
	pub fn from_bytes(buf: Bytes) -> Self {
		Self {
			inner: buf,
			..Default::default()
		}
	}

	#[inline]
	pub fn from_str(buf: &str) -> Self {
		Self {
			inner: Bytes::copy_from_slice(buf.as_bytes()),
			..Default::default()
		}
	}
}

impl FromBuf for SipURI {
	type From = Bytes;

	#[inline]
	fn from_buf_all(from: Self::From) -> Result<Self, FromBufError>
	where
		Self: Sized,
	{
		Ok(Self::from_bytes(from))
	}

	///因为sipuri可能在多种位置出现,因此当前方法不应该被调用
	#[inline]
	fn from_buf(_from: &mut Self::From) -> Result<Self, FromBufError>
	where
		Self: Sized,
	{
		Err(FromBufError::new(
			"sipuri不能使用from_buf()方法,需要使用from_buf_all()方法....",
		))
	}
}
